#pragma once
#include <iostream>
#include <string>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "Log.hpp"
#include "INetAddr.hpp"
#include <unistd.h>
#include <sys/wait.h>
#include <functional>

using task_t = std::function<std::string(const std::string&)>;

const int defaultSock = -1;
const int gBackLog = 16;

enum
{
    SOCKET_ERROR = 1,
    BIND_ERROR,
    LISTEN_ERROR
};

class UdpServer;

struct ThreadData
{
    int socket;
    INetAddr addr;
    UdpServer* uq;
    ThreadData(int sock, INetAddr address, UdpServer* usvr)
        :socket(sock), addr(address), uq(usvr)
    {}
};

class UdpServer
{
public:
    UdpServer(uint16_t port, task_t func)
        :_port(port), _listenSock(defaultSock), _isrunning(false), _func(func)
    {}
    void InitServer()
    {
        //1.创建套接字
        _listenSock = socket(AF_INET, SOCK_STREAM, 0);
        if(_listenSock < 0)
        {
            LOG(FATAL, "socket error\n");
            exit(SOCKET_ERROR);
        }
        LOG(INFO, "socket create success, sockfd: %d\n", _listenSock);

        //2.0初始化结构体字段
        struct sockaddr_in local;
        bzero(&local, sizeof local);
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY;

        //2. 绑定套接字和端口
        int n = bind(_listenSock, (const sockaddr*)&local, sizeof local);
        if(n < 0)
        {
            LOG(FATAL, "bind error\n");
            exit(BIND_ERROR);
        }
        LOG(INFO, "bind success\n");

        //3.因为tcp是面向连接的，所以通信之前必须建立连接，服务器是被连接的
        n = listen(_listenSock, gBackLog);
        if(n < 0)
        {
            LOG(FATAL, "listen error\n");
            exit(LISTEN_ERROR);
        }
        LOG(INFO, "listen success\n");
    }

    void Service(int socket, INetAddr addr)
    {
        std::string clientAddr = "[" + addr.IP() + ":" + std::to_string(addr.Port()) + "] ";
        LOG(INFO, "get a link from %s\n", clientAddr.c_str());
        while(true)
        {
            char inbuff[1024];
            ssize_t n = recv(socket, inbuff, sizeof(inbuff) - 1, 0);
            if(n > 0)
            {
                inbuff[n] = '\0';
                LOG(INFO, "%s%s\n", clientAddr.c_str(), inbuff);

                std::string message = _func(inbuff);

                send(socket, message.c_str(), message.size(), 0);
                
            }
            else if(n == 0)
            {
                LOG(INFO, "%s is quit\n", clientAddr.c_str());
                break;
            }
            else
            {
                LOG(ERROR, "%s read error\n", clientAddr.c_str());
                break;
            }
        }
        close(socket);
    }

    static void* HandlerTask(void* args)
    {
        pthread_detach(pthread_self());
        ThreadData* td = static_cast<ThreadData*>(args);
        td->uq->Service(td->socket, td->addr);
        delete td;
        return nullptr;
    }

    void Loop()
    {
        _isrunning = true;
        while(true)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof peer;
            int socket = accept(_listenSock, (sockaddr*)&peer, &len);
            if(socket < 0)
            {
                LOG(WARNING, "accept fail\n");
                continue;
            }

            //Version 2 多线程
            pthread_t tid;
            ThreadData* td = new ThreadData(socket, INetAddr(peer), this); 
            pthread_create(&tid, nullptr, HandlerTask, td);//将线程进行分离

        }
    }
    ~UdpServer()
    {}
private:
    uint16_t _port;
    int _listenSock;
    bool _isrunning;
    task_t _func;
};